package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {
    private String contextPath;
    public void init(FilterConfig filterConfig) throws ServletException {
        this.contextPath = filterConfig.getServletContext().getContextPath();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        String servletPath = request.getServletPath();
        if (this.isPermitted(servletPath, session)) {
            filterChain.doFilter(request, response);
        } else {
            String var10001 = this.contextPath;
            response.sendRedirect(var10001 + "/" + servletPath.split("/")[1] + "/page/login.jsp");
        }

    }

    public void destroy() {
    }

    public boolean isPermitted(String Path, HttpSession session) {
        if (session.getAttribute("user") != null || session.getAttribute("admin")!=null) {
            return true;
        } else {
            return Path.endsWith(".html") ||
                    Path.endsWith(".css") ||
                    Path.endsWith(".js") ||
                    Path.endsWith(".json") ||
                    Path.endsWith(".jpg") ||
                    Path.endsWith(".png") ||
                    Path.endsWith(".eot") ||
                    Path.endsWith(".svg") ||
                    Path.endsWith(".ttf") ||
                    Path.endsWith(".woff") ||
                    Path.endsWith(".woff2") ||
                    Path.endsWith(".otf") ||
                    Path.endsWith("register.jsp") ||
                    Path.endsWith("login.jsp") ||
                    Path.endsWith("LoginServlet") ||
                    Path.endsWith("RegisterServlet") ||
                    Path.endsWith("CheckEmailServlet") ||
                    Path.endsWith("CheckPhoneServlet") ||
                    Path.endsWith("CheckUnameServlet");
        }
    }
}
